/**
 * author:Administrator
 * date:2016/3/2
 * desc:TODO
 */
"use strict";

var app = require('koa')();
var path = require('path');
var config = require('./config');

// ---logger
app.use(function*(next) {
  var start = new Date();
  yield next;
  var ms = new Date() - start;
  console.log('%s %s - %s', this.method, this.url, ms);
});

// ---enable cross domain
var cors = require('koa-cors'); //解决跨域
app.use(cors({credentials: true}));
app.use(function*(next) {
  this.set("Access-Control-Allow-Origin", "*");
  this.set("Access-Control-Allow-Methods", "*");
  this.set("Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept");
  if (this.method === 'OPTIONS') {
    this.body = "Access-Control-Allow-Origin";
  } else {
    yield next;
  }
});

// static
var serve = require('koa-static');
app.use(serve(__dirname + '/ddd/ui'));

// session
app.keys = ['session_key_unique'];
var session = require('koa-session');
app.use(session(app));

// ---------------router-----------
app.use(require('./router/v1/location.js'));
app.use(require('./router/v1/category.js'));
app.use(require('./router/v1/vendor.js'));
app.use(require('./router/v1/customer.js'));
app.use(require('./router/v1/auth.js'));
// ---------------router-----------

// mannual load mock data
// node ddd/mockdata.js

// 404
app.use(function*() {
  this.status = 404;
  this.body = '~~~404 not found~~~';
});


app.listen(config.port, config.host, function () {
  console.log('server listen at %s:%s', config.host, config.port);
});